package org.kl.wx.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bf.utils.KLSearchFilter;
import org.kl.wx.entity.MessageReceive;
import org.kl.wx.repository.MessageReceiveDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class MessageReceiveService {

private MessageReceiveDao messageReceiveDao;
	
	public MessageReceive getMessageReceive(String id){
		return messageReceiveDao.find(MessageReceive.class, id);
	}
	
	public void saveMessageReceive(MessageReceive entity){
		messageReceiveDao.save(entity);
	}
	
	public void deleteMessageReceive(String id){
		messageReceiveDao.delete(id);
	}
	public List<MessageReceive> getAllMessageReceive(){
		return messageReceiveDao.findAll();
	}
	
	public String multiDelete(String ids){
		String[] idArray = StringUtils.split(ids, ",");
		int i = 0;
		for(String id : idArray){
			if(StringUtils.isNotBlank(id)){
				messageReceiveDao.delete(id);
				i++;
			}
		}
		return "成功删除" + i + "条记录";
	}
	
	/**
	 * 按条件查询
	 */
	public List<MessageReceive> getMessageReceive(Map<String, Object> searchParams) {
		Specification<MessageReceive> spec = buildSpecification(searchParams);
		return messageReceiveDao.findAll(spec);
	}
	
	/**
	 * 按条件分页查询
	 */
	public Page<MessageReceive> getMessageReceive(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<MessageReceive> spec = buildSpecification(searchParams);

		return messageReceiveDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<MessageReceive> buildSpecification(Map<String, Object> searchParams) {
		Map<String, KLSearchFilter> filters = KLSearchFilter.parse(searchParams);
		Specification<MessageReceive> spec = KLDynamicSpecifications.byKLSearchFilter(filters.values(), MessageReceive.class);
		return spec;
	}
	
	@Autowired
	public void setMessageReceiveDao(MessageReceiveDao messageReceiveDao) {
		this.messageReceiveDao = messageReceiveDao;
	}
}
